package dxunderground.utilities.ocr;

public class CaptchaImage {
	private Byte[][] value;

	/**
	 * Creates a new <code>SampleImage</code> referred to an exist 2D
	 * <code>Byte</code> array.
	 * 
	 * @param value
	 *            the Byte Array in 2-dimensions. Stored as [height][width]
	 */
	public CaptchaImage(Byte[][] value) {
		this.value = value;
	}

	public CaptchaImage(String str) {
		String[] rows = str.split("\n");
		Byte[][] value = new Byte[rows.length][rows[0].length()];
		for (int i = 0; i < rows.length; i++) {
			for (int j = 0; j < rows[i].length(); j++) {
				if (rows[i].charAt(j) == ' ')
					value[i][j] = 0;
				else
					value[i][j] = 1;
			}
		}
		this.value = value;
	}

	public Byte[][] getValue() {
		return value;
	}

	public void setValue(Byte[][] value) {
		this.value = value;
	}

	public int getWidth() {
		return this.value[0].length;
	}

	public int getHeight() {
		return this.value.length;
	}

	/**
	 * Returns a new <code>SampleImage</code> containing the required area
	 * 
	 * @param startX
	 *            X of the choping area(start with 0)
	 * @param startY
	 *            Y of the choping area(start with 0)
	 * @param width
	 *            Width of the choping area
	 * @param height
	 *            Height of the choping area
	 * 
	 * @return a <code>SampleImage</code> that is referred to the required area
	 * @throws <code>IndexOutOfBoundsException</code> if the argument is out of
	 *         bounds.
	 * 
	 */
	public CaptchaImage Chop(int startX, int startY, int width, int height) {

		if (startX < 0 || startY < 0 || width <= 0 || height <= 0 || (startX + height) > this.getHeight() || (startY + width) > this.getWidth())
			throw new IndexOutOfBoundsException("Arguments of chop are out of bounds");

		Byte[][] values = new Byte[height][width];
		for (int i = 0; i < height; i++)
			for (int j = 0; j < width; j++)
				values[i][j] = this.value[startX + i][startY + j];
		return new CaptchaImage(values);
	}

	@Override
	public String toString() {
		StringBuilder s = new StringBuilder(getHeight() * getWidth());
		for (int i = 0; i < getHeight(); i++) {
			for (int j = 0; j < getWidth(); j++) {
				if (value[i][j] == 1)
					s.append('*');
				else
					s.append(' ');
			}
			s.append('\n');
		}
		return s.toString();
	}
}
